package com.cswnode.demo.controller;


import com.cswnode.demo.entity.Page;
import com.cswnode.demo.entity.User;
import com.cswnode.demo.enums.typeEnum;
import com.cswnode.demo.service.UserService;
import com.cswnode.demo.util.Constant;
import com.cswnode.demo.util.ResponseVo;
import com.cswnode.demo.util.Utils;
import com.cswnode.demo.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author csw
 * @create 2021/2/3 14:26
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController implements Constant {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取当前登录用户信息
     * @param principal
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public ResponseVo getUser(Principal principal){
        if (null == principal){
            return null;
        }
        String name = principal.getName();
        User user = userService.queryByName(name);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        System.out.println(userVo);
        return ResponseVo.success(userVo);
    }

    /**
     * 修改用户账户
     * @param userNameOld
     * @param userNameNew
     * @return
     */
    @ApiOperation(value = "修改用户账户")
    @GetMapping("/updateUserName/{userNameOld}/{userNameNew}")
    public ResponseVo updateUserName(@PathVariable String userNameOld,@PathVariable String userNameNew){
        if (StringUtils.isEmpty(userNameOld ) || StringUtils.isEmpty(userNameNew)){
            return ResponseVo.error("原账户或新账户不能为空！");
        }
        User loginUser = Utils.getLoginUser();
        if (!(StringUtils.equals(userNameOld,loginUser.getUsername()))){
            return ResponseVo.error("原账户输入错误!");
        }
        Boolean isUserName = userService.checkExists(userNameNew);
        if (isUserName){
            return ResponseVo.error("该账户已存在！请重新输入");
        }
        User user = new User();
        user.setUserId(loginUser.getUserId());
        user.setUsername(userNameNew);
        userService.update(user);
        return ResponseVo.success("修改成功！");
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePassword")
    public ResponseVo updatePassword(String passwordOld,String passwordNew){
        Map<String, String> result = userService.updatePassword(passwordOld, passwordNew);
        if (result == null){
            return ResponseVo.success("修改成功！");
        }
        return ResponseVo.error(result.get("errorMsg"));
    }

    @ApiOperation(value = "修改用户中文名")
    @GetMapping("/updateUserNameCn/{userNameCnOld}/{userNameCnNew}")
    public ResponseVo updateUserNameCn(@PathVariable String userNameCnOld,@PathVariable String userNameCnNew){
        Map<String, String> result = userService.updateUserNameCn(userNameCnOld, userNameCnNew);
        if (result == null){
            return ResponseVo.success("修改成功！");
        }
        return ResponseVo.error(result.get("errorMsg"));
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public ResponseVo add(@RequestBody User user){
        if (ObjectUtils.isEmpty(user)){
            return ResponseVo.error("用户不能为空");
        }
        Map<String, Object> result = userService.insert(user);
        if (result.containsKey(ERROR)){
            return ResponseVo.error((String) result.get(ERROR));
        }
        return ResponseVo.success("添加成功！");

    }

    @ApiOperation(value = "获得所有用户（分页）")
    @GetMapping("/query")
    public ResponseVo query(@RequestParam(defaultValue = "1") Integer current,
                            @RequestParam(defaultValue = "10")Integer limit, String usernameCn){
        Page page = new Page();
        page.setCurrent(current);
        page.setLimit(limit);
        page.setRows(userService.selectRow(typeEnum.ADMIN.getCode(),usernameCn));
        List<User> users = userService.queryAllByLimit
                (page.getOffset(), page.getLimit(), typeEnum.ADMIN.getCode(), usernameCn);
        List<UserVo> userVos = new ArrayList<>();
        Map<String,Object> Vo = new HashMap<>();
        for (User user : users){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            userVos.add(userVo);
        }
        Vo.put("userVos",userVos);
        Vo.put("page",page);
        return ResponseVo.success(Vo);
    }

    @ApiOperation(value = "删除用户")
    @GetMapping("/delete/{userId}")
    public ResponseVo delete(@PathVariable("userId") Long userId){
        if (null == userId){
            return ResponseVo.error("用户不能为空");
        }
        boolean result = userService.deleteById(userId);
        if (result){
            return ResponseVo.success("删除成功");
        }
        return ResponseVo.success("删除失败");
    }
    @ApiOperation(value = "修改用户")
    @PostMapping("/update")
    public ResponseVo update(@RequestBody User user){
        if (ObjectUtils.isEmpty(user)){
            return ResponseVo.error("用户不能为空!");
        }
        String result = userService.updateUser(user);
        if (StringUtils.isEmpty(result)){
            return ResponseVo.success("修改成功");
        }
        return ResponseVo.error(result);
    }
}
